package com.itheima.controller;


import com.itheima.domain.Book;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/books")

public class BookController {

    @Autowired
    private BookService bookService;

    // 增
    @PostMapping
    public Result save(@RequestBody Book book) {
        Boolean b = bookService.save(book);
        System.out.println(b);
        return new Result(b ? Code.SAVE_OK : Code.SAVE_ERR,
                b ? "添加成功" : "添加失败", b);
    }
    // 删
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        Boolean b = bookService.delete(id);
        System.out.println(b);
        return new Result(b ? Code.DELETE_OK : Code.DELETE_ERR,
                b ? "删除成功" : "删除失败", b);
    }

    // 改
    @PutMapping
    public Result update(@RequestBody Book book) {
        Boolean b = bookService.update(book);
        System.out.println(b);
        return new Result(b ? Code.UPDATE_OK : Code.UPDATE_ERR,
                b ? "修改成功" : "修改失败", b);
    }

    // 查
    @GetMapping
    public Result getAll() {
        List<Book> list = bookService.getAll();
        System.out.println(list);
        return new Result(list != null ? Code.GET_OK : Code.GET_ERR,
                list != null ? "查询成功" : "查询失败", list);
    }

    // 查一个
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        if (id == 1) {
            System.out.println("抛出一个自定义异常进行测试");
            throw new SystemException(Code.SYSTEM_ERR, "我是自定义异常");
        }

        Book book = bookService.getById(id);
        System.out.println(book);
        return new Result(book != null ? Code.GET_OK : Code.GET_ERR,
                book != null ? "查询成功" : "查询失败", book);
    }


}
